#include "key.h"

ST_KEYDAT  gs_Keydata[NUM_KEY];
u8 gu8_KeyPins[NUM_KEY] = {GPIO_KEY1_OPT};

void key_init()
{
	u8 i=0;
	
	memset(gs_Keydata,0,sizeof(ST_KEYDAT)*NUM_KEY); //按键结构体数组初始化
	for (i = 0; i < NUM_KEY; i++) //key引脚循环初始化，初始值全部为低电平
	{
        device_gpio_key_init(gu8_KeyPins[i], GPIO_MODE_INPUT);
	}
}

void key_scan()
{
	u8 i=0;
	u8 lev=1;
	
	for (i = 0; i < NUM_KEY; i++)
	{
		lev = device_gpio_get(gu8_KeyPins[i]);
		if(lev == LEV_KEY_PRESSED)
		{
			gs_Keydata[i].flgPressed = 1; //按键被按下
		}
		else
        {
            gs_Keydata[i].flgPressed = 0; //按键被抬起
        }
	}
}

ENUM_KEYSTA key_get_state(u8 keyx)//遍历按键状态
{
    if(keyx < NUM_KEY)
    {
        return gs_Keydata[keyx].sta;
    }

    return KEY_STANONE;
}

void key_set_state(u8 keyx, ENUM_KEYSTA stax)
{
    if(keyx < NUM_KEY)
    {
        gs_Keydata[keyx].sta = stax;
    }
}

//更新按键状态
void key_update_sta()
{
    u8 i=0;
    //更新按键电平状态
    key_scan();
     //按键轮询计数,判断是长按还是短按
    for(i=0;i<NUM_KEY;i++)
    {
        if(gs_Keydata[i].flgPressed == 1) //长按2S的判断
        {
            gs_Keydata[i].keyCnt += KEY_SCAN_PERIOD;


            if((gs_Keydata[i].keyCnt>KEY_5SHOLD)&&(gs_Keydata[i].keyCnt<KEY_LONGTHRESHOLD2)&&!gs_Keydata[i].finishflg5s)
            {
                gs_Keydata[i].sta = KEY_STALONG_5S;
                gs_Keydata[i].finishflg5s = 1;
                LOG_INFO("dected KEY_STALONG_5S\n");
            }
            else if((gs_Keydata[i].keyCnt>KEY_SHORTHRESHOLD)&&(gs_Keydata[i].keyCnt<KEY_RECOVERYHOLD)&&!gs_Keydata[i].finishflg)
            {
                gs_Keydata[i].sta = KEY_STALONG_1S;
                gs_Keydata[i].finishflg = 1;

                LOG_INFO("dected KEY_STALONG_1S\n");
            }
        }
        else //短按的判断
        {
            if((gs_Keydata[i].keyCnt>KEY_DISTURTHRESHOLD) && (gs_Keydata[i].keyCnt<KEY_SHORTHRESHOLD) && !gs_Keydata[i].finishflg)
            {
                gs_Keydata[i].sta = KEY_STASHORT;

                gs_Keydata[i].finishflg = 1;
                LOG_INFO("dected KEY_SHORT\n");
            }
            //状态还原
            gs_Keydata[i].keyCnt = 0;
            gs_Keydata[i].finishflg = 0;
            gs_Keydata[i].finishflg5s = 0;
        }
    }
    
}